import time
from datetime import datetime, timedelta
import akshare as ak
import pandas as pd
import pathlib
from pyecharts.charts import Line
from pyecharts.globals import ThemeType
import pyecharts.options as opts
import 网格计划.model as model


idxInfo = model.GetZhongZhengHongLiIndexInfo()

dataDir = pathlib.Path(f'./data/{idxInfo.name}')
pathlib.Path(dataDir).mkdir(parents=True, exist_ok=True)

start_date = "20100101"
df = pd.DataFrame()
min_val = 0
for i, v in enumerate(idxInfo.fundList):
    df_tmp = ak.fund_etf_hist_em(symbol=v.code, start_date=start_date, adjust="qfq")
    tmp = df_tmp.describe()
    max = tmp['最高']['max']
    min = tmp['最低']['min']
    min_val = round(min * 0.9, 3)
    withdrawal_percent = 100 - round(min * 100 / max)     # 最大回撤
    cur = df_tmp.iloc[-1]["收盘"]
    cur_percent = 100 - round(cur * 100 / max)
    print(f'{v.code}-最高:{max}-最低:{min}-最大回撤：{withdrawal_percent}%-当前:{cur}-当前回撤：{cur_percent}%')
    df_tmp = df_tmp.loc[:, ["日期", "收盘"]]
    df_tmp = df_tmp.rename(columns={"收盘": v.code})
    if i == 0:
        df = df_tmp
    else:
        df = pd.merge(df, df_tmp, on="日期", how='left').fillna(0)


# 绘制图表 - 折线图
chart = Line(
    # 设置主题、画布宽度、高度等信息
    init_opts=opts.InitOpts(theme=ThemeType.DARK, width="1400px", height="600px"),
)

# 全局设置
chart.set_global_opts(
    title_opts=opts.TitleOpts(title=f'{idxInfo.name}-基金列表'),
    # 工具箱配置
    toolbox_opts=opts.ToolboxOpts(is_show=True),
    # 区域缩放配置
    datazoom_opts=[opts.DataZoomOpts(is_show=True, range_start=0, range_end=100)],
    # y轴配置
    yaxis_opts=opts.AxisOpts(
        min_=min_val,  # 设置y轴刻度间隔为20
    )
)

chart.add_xaxis(xaxis_data=df["日期"].tolist())  # 添加x轴数据
for fund in idxInfo.fundList:
    chart.add_yaxis(
        series_name=fund.code,
        y_axis=df[fund.code].tolist(),  # y轴数据
        is_connect_nones=True,  # 连接空数据
        markpoint_opts=opts.MarkPointOpts(
            data=[opts.MarkPointItem(type_="max"), opts.MarkPointItem(type_="min")],
        ),
    )
date = time.strftime('%Y%m%d', time.localtime(time.time()))
chart.render(f"{dataDir}/ETF基金历史行情-{idxInfo.name}-{date}.html")

